//
//  ChannelNetEventhandler.m
//  gzline
//
//  Created by hsm on 3/26/13.
//
//

#import "PokerNetEventhandler.h"
#import "DDXML.h"
#import <SystemConfiguration/SystemConfiguration.h>
#import <netinet/in.h>
#import "PokerControlClient.h"
#import "RemoteControlClient.h"

SCNetworkReachabilityRef reachability;

@implementation PokerNetEventHandler
//@synthesize socket,xmlParser;
@synthesize deletate;

#pragma -
#pragma ---

-(id)init {
    self = [super init];
    socket=[[AsyncSocket alloc] initWithDelegate:self];
    [self performSelector:@selector(setupNetworkMonitoring)];
    xmlParser=nil;
    recvData = [[NSMutableData alloc] init];
    return self;
}

#pragma -
#pragma client request method

-(void)connectToHost:(NSString*)ip onPort:(NSInteger)aPort {
    NSError *error = nil;
//    NSLog(@"connect to host  ip:%@ port:%d", ip, aPort);
    [socket connectToHost:ip onPort:aPort withTimeout:30 error:&error];
}
-(void)acceptOnPort:(UInt16)port {
    NSError *error = nil;
    [socket acceptOnPort:port error:&error];
}
-(void)sendString:(NSString*)str {
    NSLog(@"SEND: %@", str);
    [socket writeData:[str dataUsingEncoding:NSUTF8StringEncoding] withTimeout:30 tag:0];
}
-(void)sendNetData:(NSData *)netData{
    //    NSLog(@"SEND: %@", dataxx);
    [socket writeData:netData withTimeout:30 tag:0];
}
-(void)sendElement:(DDXMLElement*)xmlElement {
    NSString *xmlStr = [xmlElement compactXMLString];
    [self sendString:xmlStr];
}

-(BOOL)isConnected {
    
    return [socket isConnected];
}

-(void)disconnect {
    [socket disconnect];
}


#pragma -
#pragma asyncsocket delegate methods

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err {
//    NSLog(@"willDisconnectWithError:%@",[err localizedDescription]);
}

- (void)onSocketDidDisconnect:(AsyncSocket *)sock {
//    NSLog(@"onSocketDidDisconnect");
    if (xmlParser) {
        [xmlParser release];
        xmlParser = nil;
    }
}

- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket {
    NSLog(@"didAcceptNewSocket");
    [socket readDataWithTimeout:-1 tag:0];
    if (xmlParser) {
        [xmlParser release];
        xmlParser = nil;
    }
    xmlParser = [[XMPPParser alloc] initWithDelegate:self];
}

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
    [socket readDataWithTimeout:-1 tag:0];
    if (xmlParser) {
        [xmlParser release];
        xmlParser = nil;
    }
    xmlParser = [[XMPPParser alloc] initWithDelegate:self];
    [deletate performSelector:@selector(didConnect)];
//    NSLog(@"didConnectToHost");
}

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    [sock readDataWithTimeout:-1 tag:0];
//    [xmlParser parseData:data];//收到数据，调用xml解析器
//    return;
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    if (str) {
        NSLog(@"RECV:%@", str);
    }
    if ([str hasPrefix:@"<data>"]) {
        [recvData resetBytesInRange:NSMakeRange(0, [recvData length])];
        [recvData setLength:0];
    }
    [recvData appendData:data];
    if ([str hasSuffix:@"</data>"]) {
        [recvData appendData:data];
        [xmlParser parseData:recvData];//收到数据，调用xml解析器
    }
    if ([[PokerControlClient share].ctrlPort intValue] == import_port) {
        
//        [xmlParser parseData:data];//收到数据，调用xml解析器
        
    }else{
        NSString *str1 = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
        //    NSLog(@"REMOTE RECV :%@", str1);
        if ([str1 hasPrefix:@"@@"]) {
//            NSLog(@"REMOTE RECV :%@", str1);
            [deletate  performSelector:@selector(recvData:) withObject:data] ;
        }else{
            [deletate  performSelector:@selector(recvStr:) withObject:str];
        }
        [str1 release];
    }
    [str release];
}


- (void)onSocket:(AsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag {
    NSLog(@"didReadPartialDataOfLength:%d",partialLength);
}


#pragma -
#pragma xml parse callback
- (void)xmppParser:(XMPPParser *)sender didReadRoot:(DDXMLElement *)root {
    //NSLog(@"didReadRoot:%@",[root name]);
    
    [deletate  performSelector:@selector(streamDidOpen:) withObject:root  ] ;
}

- (void)xmppParser:(XMPPParser *)sender didReadElement:(DDXMLElement *)element {
//    NSLog(@"didReadElement:%@",[element name]);
//    NSString *nick = [element attributeStringValueForName:@"data"];
    [deletate performSelector:@selector(didReadElement:) withObject:element];
}

- (void)xmppParserDidEnd:(XMPPParser *)sender {
    NSLog(@"xmppParserDidEnd");
    [socket disconnect];
}

- (void)xmppParser:(XMPPParser *)sender didFail:(NSError *)error {
//    NSLog(@"didFail %@",error);
//    [socket disconnect];
}

#pragma -
#pragma other

-(NSString*)currentNetworkType {
    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
	
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    NSString *networkType = @"iOS-WIFI";
    if (flags & kSCNetworkReachabilityFlagsIsWWAN) {
        // 3G/Edge/GPRS
        networkType = @"iOS-GPRS";
        NSLog(@"Net changed to GPRS");
    }
    return networkType;
}

#pragma -
#pragma network status management
static void ReachabilityChanged(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void *info) {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSLog(@"网络状态改变:%@,%d,%@",target, flags, info);
    [[PokerControlClient share] performSelector:@selector(networkStateChanged) withObject:nil];
	[pool release];
}



-(void)setupNetworkMonitoring {
	reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [@"117.135.132.61" UTF8String]);
    if (reachability) {
        SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
        SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
        SCNetworkReachabilitySetCallback(reachability, ReachabilityChanged, &context);
    }
}

-(void)teardownNetworkMonitoring {
	if (reachability) {
		SCNetworkReachabilityUnscheduleFromRunLoop(reachability, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
		CFRelease(reachability);
		reachability = NULL;
	}
}


-(void)dealloc {
    [socket disconnect];
    [self performSelector:@selector(teardownNetworkMonitoring)];
    [socket release];
    [xmlParser release];
    [super dealloc];
}



@end